package com.allwe.client.singleGroup;

import com.allwe.client.partitioner.MyPartitioner;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.Scanner;

/**
 * kafka生产者配置 - 无限生产消息
 *
 * @Author: AllWe
 * @Date: 2024/09/24/17:57
 */
@Slf4j
public class Producer {
    public static void main(String[] args) {
        // 设置属性
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "39.107.66.31:9092");
        properties.put("key.serializer", StringSerializer.class);
        properties.put("value.serializer", StringSerializer.class);
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, MyPartitioner.class);

        // new一个生产者producer
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
        Scanner scanner = new Scanner(System.in);;
        try {
            int count;
            while (true) {
                System.out.println("==================输入消息条数===================");
                String nextLine = scanner.nextLine();
                if ("exit".equals(nextLine)) {
                    break;
                }
                count = Integer.parseInt(nextLine);
                ProducerRecord<String, String> producerRecord;
                try {
                    for (int i = 0; i < count; i++) {
                        // 构建消息
                        producerRecord = new ProducerRecord<>("topic_5", "topic_5", "allwe" + i);
                        producer.send(producerRecord);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("发送完成,topic_5");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 释放连接
            producer.close();
            scanner.close();
        }
    }
}
